# static_type_examples.py
"""
MicroPython 协作开发指南 - 静态类型注解标准示例
MicroPython Collaborative Development Guide - Standard Static Type Annotation Examples

MicroPython 兼容的类型注解示例，均兼容 mypy 和 pyright 静态类型检查
MicroPython-compatible type annotation examples, compatible with mypy and pyright static type checking

注意：在 MicroPython 中运行时，类型注解会被忽略但不会报错
Note: Type annotations are ignored but don't cause errors when running in MicroPython
"""

from typing import Optional, Union, List, Dict, Tuple, Set, Any


def add(x: int, y: int) -> int:
    """整数加法 | Integer addition"""
    return x + y


def greet(name: str) -> str:
    """字符串问候 | String greeting"""
    return "Hello, " + name + "!"


def get_pi() -> float:
    """浮点数返回 | Float return"""
    return 3.14159


def is_even(n: int) -> bool:
    """布尔值判断 | Boolean check"""
    return n % 2 == 0


def do_nothing() -> None:
    """无返回值 | No return value"""
    pass


def squares(nums: List[int]) -> List[int]:
    """列表处理 | List processing"""
    return [n * n for n in nums]


def phonebook() -> Dict[str, int]:
    """字典返回 | Dictionary return"""
    return {"Alice": 123, "Bob": 456}


def split_name(full: str) -> Tuple[str, str]:
    """元组返回 | Tuple return"""
    parts = full.split(" ")
    if len(parts) >= 2:
        return (parts[0], parts[1])
    return (parts[0], "")


def unique_numbers(nums: List[int]) -> Set[int]:
    """集合返回 | Set return"""
    return set(nums)


def find_user(users: List[str], name: str) -> Optional[str]:
    """可选类型返回 | Optional type return"""
    for user in users:
        if user == name:
            return user
    return None


def process_data(data: Union[str, int, float]) -> str:
    """联合类型处理 | Union type processing"""
    if isinstance(data, str):
        return f"String: {data}"
    elif isinstance(data, int):
        return f"Integer: {data}"
    else:
        return f"Float: {data:.2f}"


def flexible_function(*args: Any, **kwargs: Any) -> Dict[str, Any]:
    """灵活参数函数 | Flexible parameter function"""
    return {
        "args": args,
        "kwargs": kwargs,
        "args_count": len(args),
        "kwargs_count": len(kwargs)
    }


class TypedDevice:
    """
    带类型注解的设备类 | Typed device class
    用于演示类的类型注解 | Demonstrates class type annotations
    """
    
    def __init__(self, device_id: int, name: str) -> None:
        """
        初始化设备 | Initialize device
        
        参数 Parameters:
        - device_id (int): 设备ID | Device ID
        - name (str): 设备名称 | Device name
        """
        self.device_id: int = device_id
        self.name: str = name
        self.is_active: bool = False
        self.properties: Dict[str, Any] = {}
    
    def activate(self) -> bool:
        """激活设备 | Activate device"""
        self.is_active = True
        return self.is_active
    
    def set_property(self, key: str, value: Any) -> None:
        """设置属性 | Set property"""
        self.properties[key] = value
    
    def get_property(self, key: str, default: Any = None) -> Any:
        """获取属性 | Get property"""
        return self.properties.get(key, default)
    
    def get_status(self) -> Dict[str, Any]:
        """获取设备状态 | Get device status"""
        return {
            "id": self.device_id,
            "name": self.name,
            "active": self.is_active,
            "properties": self.properties
        }


# MicroPython 测试示例 | MicroPython test examples
def test_examples() -> None:
    """测试所有示例函数 | Test all example functions"""
    print("Testing MicroPython-compatible examples:")
    print("=" * 50)
    
    # 测试基础类型 | Test basic types
    print("Basic Types | 基础类型:")
    print(f"add(5, 3) = {add(5, 3)}")
    print(f"greet('World') = {greet('World')}")
    print(f"get_pi() = {get_pi()}")
    print(f"is_even(4) = {is_even(4)}")
    print(f"is_even(5) = {is_even(5)}")
    
    # 测试集合类型 | Test collection types
    print("\nCollection Types | 集合类型:")
    nums = [1, 2, 3, 4]
    print(f"squares({nums}) = {squares(nums)}")
    print(f"phonebook() = {phonebook()}")
    print(f"split_name('John Doe') = {split_name('John Doe')}")
    print(f"unique_numbers([1,2,2,3]) = {unique_numbers([1,2,2,3])}")
    
    # 测试可选类型 | Test optional types
    print("\nOptional Types | 可选类型:")
    users = ['Alice', 'Bob']
    print(f"find_user({users}, 'Alice') = {find_user(users, 'Alice')}")
    print(f"find_user({users}, 'Charlie') = {find_user(users, 'Charlie')}")
    
    # 测试联合类型 | Test union types
    print("\nUnion Types | 联合类型:")
    print(f"process_data('hello') = {process_data('hello')}")
    print(f"process_data(42) = {process_data(42)}")
    print(f"process_data(3.14) = {process_data(3.14)}")
    
    # 测试灵活参数 | Test flexible parameters
    print("\nFlexible Parameters | 灵活参数:")
    result = flexible_function(1, 2, 3, name="test", value=42)
    print(f"flexible_function(1, 2, 3, name='test', value=42) = {result}")
    
    # 测试类类型注解 | Test class type annotations
    print("\nClass Type Annotations | 类类型注解:")
    device = TypedDevice(1, "Sensor")
    print(f"Device created: {device.get_status()}")
    
    device.activate()
    device.set_property("temperature", 25.5)
    device.set_property("humidity", 60)
    print(f"Device after activation: {device.get_status()}")
    
    print("\n" + "=" * 50)
    print("All tests completed successfully! | 所有测试成功完成！")


def demonstrate_type_checking() -> None:
    """
    演示类型检查功能 | Demonstrate type checking functionality
    
    这个函数包含一些故意的类型错误，用于测试静态类型检查器
    This function contains some intentional type errors to test static type checkers
    """
    print("Type Checking Demonstration | 类型检查演示:")
    
    # 正确的类型使用 | Correct type usage
    correct_result: int = add(5, 3)
    print(f"Correct: add(5, 3) = {correct_result}")
    
    # 以下注释的代码包含类型错误，用于测试 mypy/pyright
    # The following commented code contains type errors for testing mypy/pyright
    
    # 类型错误示例 1: 传递错误类型的参数
    # Type error example 1: Passing wrong type arguments
    # wrong_result = add("5", "3")  # Error: Expected int, got str
    
    # 类型错误示例 2: 将函数结果赋值给错误类型的变量
    # Type error example 2: Assigning function result to wrong type variable
    # wrong_assignment: str = add(5, 3)  # Error: Expected str, got int
    
    # 类型错误示例 3: 调用不存在的方法
    # Type error example 3: Calling non-existent method
    # result = "hello".non_existent_method()  # Error: Method does not exist
    
    print("Type checking demonstration completed | 类型检查演示完成")


if __name__ == "__main__":
    print("MicroPython 静态类型注解标准示例")
    print("MicroPython Standard Static Type Annotation Examples")
    print("=" * 60)
    
    # 运行所有测试 | Run all tests
    test_examples()
    
    print("\n")
    demonstrate_type_checking()
    
    print(f"\n运行建议 | Running Suggestions:")
    print("1. 在 MicroPython REPL 中运行:")
    print("   Run in MicroPython REPL:")
    print("   >>> exec(open('static_type_examples.py').read())")
    
    print("\n2. 使用类型检查器检查:")
    print("   Use type checkers:")
    print("   $ mypy static_type_examples.py")
    print("   $ pyright static_type_examples.py")
